package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.ProjTaskService;
import com.google.project.client.Service.ProjTaskServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.ProjectStaffService;
import com.google.project.client.Service.ProjectStaffServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectStaffDTO;
import com.google.project.shared.ProjectTaskDTO;


public class PMCreateProjectPlan extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField Button btnPMProjectTask;
	@UiField Button btnSearch;
	@UiField(provided = true) CellTable<ProjectTaskDTO> ctbTaskList = new CellTable<ProjectTaskDTO>();
	@UiField SimplePager pager;
	@UiField Button button;
	@UiField Button button_1;
	@UiField ListBox cboTaskType;
	@UiField ListBox cboStatus;
	@UiField ListBox cboOperator;
	@UiField TextBox txtTaskName;
	@UiField Label lblProject;
	@UiField ListBox cboParentTask;
	@UiField Button btnReqPlan;
	@UiField Button button_2;
	

	interface Binder extends UiBinder<Widget, PMCreateProjectPlan> {
	}
	
	//_________________________Common varius___________________________________
	
	private String projectID;
	ProjectDTO currProject = new ProjectDTO();
	CommonFuntion common = new CommonFuntion();
	private List<ProjectTaskDTO> listTask = new ArrayList<ProjectTaskDTO>();

	private final ProjectServiceAsync projectService = GWT.create(ProjectService.class);
	private final ProjTaskServiceAsync projectTaskService = GWT.create(ProjTaskService.class);
	private final ProjectStaffServiceAsync projectStaffService = GWT.create(ProjectStaffService.class);
	final MultiSelectionModel<ProjectTaskDTO> selectionModel = new MultiSelectionModel<ProjectTaskDTO>();
	

	//END_________________________Common varius________________________________

	
	//___________________________Contructor____________________________________
	public PMCreateProjectPlan() {

		initWidget(binder.createAndBindUi(this));
		initTable();
		bindData();
	}

	public PMCreateProjectPlan(String projectId) {
		this.projectID = projectId;
		initWidget(binder.createAndBindUi(this));
		projectService.getProjectById(projectId, new AsyncCallback<ProjectDTO>() {
			
			@Override
			public void onSuccess(ProjectDTO result) {
				// TODO Auto-generated method stub
				currProject = result;
				lblProject.setText("Dự án : "+ result.getProjectName());
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
		initTable();
		bindData();
		loadDataForCbo();
		
	}

	//End___________________________Contructor____________________________________
	

	//______________________________Common function_______________________________


	public void loadDataForCbo()
	{
		//load  for task type
		cboTaskType.addItem("Tất cả","0");
		cboTaskType.addItem("Công việc gốc","1");
		cboTaskType.addItem("Mốc mục tiêu","2");
		cboTaskType.addItem("Công việc cha","3");
		cboTaskType.addItem("Công việc con","4");
		
		//load for status
		cboStatus.addItem("Tất cả","-1");
		cboStatus.addItem("Chưa bắt đầu","0");
		cboStatus.addItem("Ðang tiến hành","1");
		cboStatus.addItem("Ðã hoàn thành","2");
		cboStatus.addItem("Ngừng thực hiện","3");
		
		
		//load for operator
		
		cboOperator.addItem("Tất cả","-1");
		projectStaffService.getProjectStaffList(projectID, new AsyncCallback<List<ProjectStaffDTO>>() {
			
			@Override
			public void onSuccess(List<ProjectStaffDTO> result) {
				// TODO Auto-generated method stub
				for(ProjectStaffDTO staff:result)
					{
						if(staff.getPosition()==3)
						{
							cboOperator.addItem(staff.getUserName(),staff.getUserId());
						}
					}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});

		
	}
	
	public void bindData() {
		projectService.getListTask(projectID, new AsyncCallback<List<ProjectTaskDTO>>() {
			
			@Override
			public void onSuccess(List<ProjectTaskDTO> result) {
				// TODO Auto-generated method stub
				LoadDataForTable(result);
				listTask = result;
				cboParentTask.addItem("Tất cả","-1");
				cboParentTask.addItem("Không có công việc cha","0");
				for(ProjectTaskDTO task : listTask)
				{
					if(task.getGroup()==1)
					{
						cboParentTask.addItem(task.getTaskName(),task.getId());
					}
					
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert("không thể load dữ liệu");
			}
		});
	
	}
	 public void initTable()
	 {
		 ctbTaskList.setSelectionModel(selectionModel,
				    DefaultSelectionEventManager.<ProjectTaskDTO> createCheckboxManager());
				Column<ProjectTaskDTO, Boolean> checkColumn = new Column<ProjectTaskDTO, Boolean>(
				    new CheckboxCell(true, false)) {
				  @Override
				  public Boolean getValue(ProjectTaskDTO object) {
				    // Get the value from the selection model.
				    return selectionModel.isSelected(object);
				  }
				};
				
				
				TextColumn<ProjectTaskDTO> stt = new TextColumn<ProjectTaskDTO>() {
					@Override
					public String getValue(ProjectTaskDTO task) {
						return task.getSTT();
					}
				};
			

			TextColumn<ProjectTaskDTO> startDate = new TextColumn<ProjectTaskDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(ProjectTaskDTO task) {
					Date startDate = new Date(task.getStartDate());
					return startDate.getDate() + "/" + (startDate.getMonth() + 1)
							+ "/" + (startDate.getYear() + 1900);
				}
			};
			TextColumn<ProjectTaskDTO> dueDate = new TextColumn<ProjectTaskDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(ProjectTaskDTO task) {
					Date dueDate = new Date(task.getDueDate());
					return dueDate.getDate() + "/" + (dueDate.getMonth() + 1) + "/"
							+ (dueDate.getYear() + 1900);
				}
			};
			
			TextColumn<ProjectTaskDTO> finishDate = new TextColumn<ProjectTaskDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(ProjectTaskDTO task) {
					
					if(task.getFinishDate()==null)
					{
						return "__";
					}
					Date finishDate = new Date(task.getFinishDate());
					
					return finishDate.getDate() + "/" + (finishDate.getMonth() + 1) + "/"
							+ (finishDate.getYear() + 1900);
				}
			};
			TextColumn<ProjectTaskDTO> amountOfWork = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					return task.getAmountOfWork().toString()+ " "+task.getUnit();
				}
			};
			
			TextColumn<ProjectTaskDTO> weight = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					return task.getWeight().toString()+"%";
				}
			};


			Column<ProjectTaskDTO, String> taskNameColumn = new Column<ProjectTaskDTO, String>(
					new ClickableTextCell()) {
				@Override
				public String getValue(ProjectTaskDTO object) {
					return object.getTaskName();
				}
			};
			taskNameColumn
			.setFieldUpdater(new FieldUpdater<ProjectTaskDTO, String>() {

				@Override
				public void update(int index, ProjectTaskDTO task,
						String value) {
					PMEntrypoint.get().PMProjectTask(task.getId(),
							currProject);
				}

			});
			
		
			TextColumn<ProjectTaskDTO> resource = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					String name="---";
					if(task.getOptAccountName()!=null && !task.getOptAccountName().equalsIgnoreCase("")){
						name=task.getOptAccountName().toString();
					}
					return name;
				}
			};
			TextColumn<ProjectTaskDTO> status = new TextColumn<ProjectTaskDTO>() {
				@Override
				public String getValue(ProjectTaskDTO task) {
					if(task.getStatus()==0)
					{
						return"Chưa bắt đầu";
					}
					if(task.getStatus()==1)
					{
						return"Đang tiến hành";
					}
					if(task.getStatus()==2)
					{
						return"Đã hoàn thành";
					}
					if(task.getStatus()==3)
					{
						return"Ngừng thực hiện";
					}
					return "";
				}
			};
			taskNameColumn.setCellStyleNames("celltable");
			
            ctbTaskList.setStyleName("ttable");
            ctbTaskList.addColumn(stt, "STT");
            ctbTaskList.setColumnWidth(stt, 4, Unit.PCT);
			ctbTaskList.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
			ctbTaskList.setColumnWidth(checkColumn, 4, Unit.PCT);
			ctbTaskList.addColumn(taskNameColumn, "Tên công việc");
			ctbTaskList.setColumnWidth(taskNameColumn, 25, Unit.PCT);
			ctbTaskList.addColumn(amountOfWork, "Khối lượng");
			ctbTaskList.setColumnWidth(amountOfWork, 10, Unit.PCT);
			//ctbTaskList.addColumn(unit,"Ðon v?");
			ctbTaskList.addColumn(weight,"Trọng số(%)");
		//	ctbTaskList.setColumnWidth(weight, 10, Unit.PCT);
			ctbTaskList.addColumn(resource,"Người thực hiện");
			//ctbTaskList.setColumnWidth(resource, 16, Unit.PCT);
			ctbTaskList.addColumn(startDate, "Ngày bắt đầu");
			//ctbTaskList.setColumnWidth(startDate, 16, Unit.PCT);
			ctbTaskList.addColumn(dueDate, "KT dự kiến");
			ctbTaskList.addColumn(finishDate, "KT thực tế");
	
			ctbTaskList.addColumn(status, "Tình trạng");
			//ctbTaskList.setColumnWidth(dueDate, 16, Unit.PCT);
			//ctbTaskList.addColumn(deleteColumn, "");

	 }
	public void LoadDataForTable(List<ProjectTaskDTO> taskList) {
		
		ListDataProvider<ProjectTaskDTO> dataProvider = new ListDataProvider<ProjectTaskDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbTaskList);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		// SimplePager
		pager.setDisplay(ctbTaskList);
		pager.setPageSize(5);
		int count =1;
		List<ProjectTaskDTO> list = dataProvider.getList();
		for (ProjectTaskDTO task : taskList) {
			task.setSTT(count+"");
			count ++;
			list.add(task);
			
		}
	}
	ProjectTaskDTO getFromlist(String taskId)
	{
		
		for(ProjectTaskDTO task:listTask)
		{
			if(task.getId().equals(taskId))
			{
				return task;
			}
			
		}
		return null;
	}
	void search()
	{

		Boolean searchCondition =true;
		 List<ProjectTaskDTO> seachResult = new ArrayList<ProjectTaskDTO>();
		 String ParentValue = cboParentTask.getValue(cboParentTask.getSelectedIndex());
			String subTask ="";
			ProjectTaskDTO parent = new ProjectTaskDTO();
			if(!ParentValue.equals("-1")&&!ParentValue.equals("0"))
			{
				parent = getFromlist(ParentValue);
				if(parent.getSubTasks()!=null&&!parent.getSubTasks().equals(""))
				{
					subTask=parent.getSubTasks();
				}
			}
		for(ProjectTaskDTO task : listTask)
		{
			searchCondition =true;
			if(!subTask.equals(""))
			{  
				searchCondition=searchCondition&&CommonFuntion.checkContain(subTask, ""+task.getTaskId());	
				}

		
			//kiem tra type
			String taskType = cboTaskType.getValue(cboTaskType.getSelectedIndex());
			if(taskType.equals("1"))
			{
				searchCondition=searchCondition&&(task.getParentId()==0);
			}
			if(taskType.equals("2"))
			{
				searchCondition=searchCondition&&(task.getIsMile()==1);
			}
			if(taskType.equals("3"))
			{
				searchCondition=searchCondition&&(task.getGroup()==1);
			}
			if(taskType.equals("4"))
			{
				searchCondition=searchCondition&&((task.getSubTasks()==null||task.getSubTasks().equals(""))&& task.getIsMile()==0);
			}
			
			//kiem tra status
			String status = cboStatus.getValue(cboStatus.getSelectedIndex());
			if(!status.equals("-1"))
			{
				searchCondition=searchCondition&&(task.getStatus()==Integer.parseInt(status));
			}
			
			String operator = cboOperator.getValue(cboOperator.getSelectedIndex());
			
			if(!operator.equals("-1"))
			{
				searchCondition=searchCondition&&(task.getOptUserId().equals(operator));
			}
			
			
			if(txtTaskName.getValue()!=null&&!txtTaskName.getValue().trim().equals(""))
			{
				searchCondition=searchCondition&&task.getTaskName().toLowerCase().contains(txtTaskName.getValue().trim().toLowerCase());
			
			}
			if(searchCondition)
			{
				seachResult.add(task);
			}
		}
		
		LoadDataForTable(seachResult);
	}
	//__________________________________Event ____________________________________

	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		search();
	}
	//tao task moi
	@UiHandler("btnPMProjectTask")
	void onBtnPMProjectTaskClick(ClickEvent event) {
		if(currProject.getStatus()==2||currProject.getStatus()==3)
		{
			Window.alert("Bạn không thể thêm công việc cho dự án đã được kết thúc");
		}
		else
		{
		PMEntrypoint.get().PMProjectTask(this.currProject);
		}
		
	}
	//ve ke hoach du an
	@UiHandler("button")
	void onButtonClick(ClickEvent event) {
		//PMEntrypoint.get().PMProjectDetail(projectID);
		PMEntrypoint.get().callPop(projectID);
	}
	
	//xoa qua check box
	@UiHandler("button_1")
	void onButton_1Click(ClickEvent event) {
		Boolean check = true;
		Set<ProjectTaskDTO> listChecked = selectionModel.getSelectedSet();
		List<ProjectTaskDTO> list = new ArrayList<ProjectTaskDTO>();
		for (ProjectTaskDTO task : listChecked) {
		  
			list.add(task);
			  if(task.getStatus()!=0)
			    {
			    	check = false;
			    	Window.alert("Bạn không thể xóa công việc đã được bắt đầu hoặc kết thúc");
			       break;
			    
			    }
		}
		if(list!=null&&list.size()>0)
		{
			if(check)
			{
				if (Window.confirm("Bạn có muốn xóa công việc đã chọn không?")) {
					projectTaskService.deleteListTask(list, listTask, new AsyncCallback<Void>() {
						
						@Override
						public void onSuccess(Void result) {
							// TODO Auto-generated method stub
							Window.confirm("Xóa thành công?");	
							projectService.getListTask(projectID, new AsyncCallback<List<ProjectTaskDTO>>() {
								
								@Override
								public void onSuccess(List<ProjectTaskDTO> result) {
									// TODO Auto-generated method stub
									
									listTask = result;
									search();
								}
								
								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									Window.alert("không thể load dữ liệu");
								}
							});
							
						}
						
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							Window.confirm("Xóa không thành công?");
						}
					});

					
				}
			}
	
		
		}
		else
		{
			Window.confirm("Bạn phải chọn công việc để xóa");
		}		
		selectionModel.clear();
	}
	
	@UiHandler("btnReqPlan")
	void onBtnReqPlanClick(ClickEvent event) {
		Boolean check = true;
		Set<ProjectTaskDTO> listChecked = selectionModel.getSelectedSet();
		List<ProjectTaskDTO> list = new ArrayList<ProjectTaskDTO>();
		for (ProjectTaskDTO task : listChecked) {
		  
			list.add(task);
			 
		}
		if(list.size()>1){
			Window.alert("Chỉ được chọn một công việc trước khi yêu cầu nhân sự!");
			check=false;
		}else if(list.size()==0){
			Window.alert("Chọn một công việc trước khi yêu cầu nhân sự!");
		}else if(list.size()==1){
			// chuyển sang TaskReqDialog
			ProjectTaskDTO task=list.get(0);
			if(task.getStatus()!=0){
				Window.alert("Yêu cầu không được thực hiện! Công việc đang tiến hành hoặc đã kết thúc!");
			}else{
				if((task.getSubTasks()==null || task.getSubTasks().equals(""))&& task.getIsMile()==0){
					PMTaskRequireDialog dialog = new PMTaskRequireDialog(
							task, currProject);
					dialog.setPopupPosition(345, 100);
					dialog.show();
				}else{
					Window.alert("Yêu cầu không được thực hiện! Công việc yêu cầu không được chứa công việc khác!");
				}
			}
			
		}
		
	}

	@UiHandler("button_2")
	void onButton_2Click(ClickEvent event) {
		Set<ProjectTaskDTO> listChecked = selectionModel.getSelectedSet();
		List<ProjectTaskDTO> list = new ArrayList<ProjectTaskDTO>();
		for (ProjectTaskDTO task : listChecked) {
		  
			list.add(task);
			 
		}
		if(list.size()>1)
		{
			Window.alert("Bạn chỉ có thể chọn 1 công việc để bổ xung tài liệu");
		}
		if(list.size()==0)
		{
			Window.alert("Bạn phải chọn công việc để bổ xung tài liệu");
		}
		if(list.size()==1)
		{
			PMEntrypoint.get().ListDocuments(list.get(0).getId(), "21", currProject.getProjectName(), list.get(0).getTaskName());
		}
		
	}

}
